import { createRouter, createWebHistory } from 'vue-router'

import { useAuthStore, authLogin, getBusiUriQuery } from '@/store/auth'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/home/index.vue'),
    meta: {
      title: '直播点播'
    }
  },
  {
    path: '/add',
    name: 'NewLive',
    component: () => import('@/views/home/live-add.vue'),
    meta: {
      title: '新建直播'
    }
  },
  {
    path: '/edit',
    name: 'EditLive',
    component: () => import('@/views/home/live-add.vue'),
    meta: {
      title: '编辑直播'
    }
  },
  {
    path: '/info',
    name: 'LiveInof',
    component: () => import('@/views/home/live-info.vue'),
    meta: {
      title: '直播详情'
    }
  },
  {
    path: '/video-detail',
    name: 'VideoDetail',
    component: () => import('@/views/home/video-detail.vue'),
    meta: {
      title: '点播详情'
    }
  },
  {
    path: '/live-detail',
    name: 'LiveDetail',
    component: () => import('@/views/home/live-detail.vue'),
    meta: {
      title: '直播详情'
    }
  },
  {
    path: '/auth',
    name: 'Auth',
    component: () => import('@/views/login/auth.vue')
  },
  {
    path: '/404',
    name: 'Error404',
    component: () => import('@/views/error/error-404.vue')
  },
  {
    path: '/:pcatchAll(.*)*',
    redirect: '/404',
    meta: { hidden: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeEach(async(to, from, next) => {
  document.title = to.meta.title || '直播点播'
  const authStore = useAuthStore()
  const token = authStore.getTooken()
  // 临时code
  const getcode = sessionStorage.getItem('LOGIN_CODE')
  if (getcode) {
    sessionStorage.removeItem('LOGIN_CODE')
    // 刷新一下路由
    history.go(0)
    return
  }
  if (token) {
    next()
  } else {
    if (to.name === 'Auth') {
      const code = to.query.code
      if (code) {
        const { code, busiUri } = getBusiUriQuery(location.href)
        authStore.loginByCode(code, () => {
          sessionStorage.setItem('LOGIN_CODE', code)
          history.back()
          location.href = busiUri
        })
      } else {
        next()
      }
    } else {
      authLogin(to.fullPath)
    }
  }
})

export default router
